package com.baosight.xCyber.service.impl;

import com.baosight.hdjni.HDErrcode;
import com.baosight.hdsdk.HDDataProvider;
import com.baosight.hdsdk.HDDataWriter;
import com.baosight.hdsdk.HDTagManager;
import com.baosight.hdsdk.domain.data.HDBasicTag;
import com.baosight.hdsdk.domain.data.HDRecord;
import com.baosight.hdsdk.exception.HDSdkException;
import com.baosight.xCyber.model.TagDetail;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;

@Service
public class TagService {

    private static Log logger = LogFactory.getLog(TagService.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //查询某个tag在一个时间段内的数据记录
    public List<TagDetail> getTagDetailList(String key, Date startTime, Date endTime){
        Environment environment = applicationContext.getEnvironment();
        String iHDBServer = environment.getProperty("iHyperDB.server");
        //判读是否存在iHDB连接
        if(iHDBServer != null){
            HDTagManager manager = applicationContext.getBean(HDTagManager.class);
            HDDataProvider provider = applicationContext.getBean(HDDataProvider.class);
            try {
                if(!Pattern.matches("^[0-9]*$",key)){
                    key = redisTemplate.opsForHash().get("codes",key).toString();
                }

                int tagID = Integer.parseInt(key);
                HDBasicTag tag = manager.getBasicTagById(tagID);
                List<HDRecord> records = provider.queryTagHisRawRecords(tagID,startTime,endTime);

                List<TagDetail> tagDetails = new ArrayList<>();
                for(HDRecord record:records){
                    TagDetail tagDetail = new TagDetail();
                    tagDetail.id = tagID;
                    tagDetail.name = tag.getName();
                    tagDetail.valueStr = record.getValueStr();
                    tagDetail.quality = record.getQuality();
                    tagDetail.tagDataType = record.getDataType();
                    tagDetail.desc = tag.getDesc();
                    tagDetail.second = record.getTimeStampStr();
                    tagDetails.add(tagDetail);
                }
                return tagDetails;

            } catch (HDSdkException e) {
                logger.error("节点记录查询失败："+e.getMessage());
            }
        }
        return null;
    }

    //查询tagId获取tagName（粒度小）
    public String getTagIDByTagName(String tagName){
        return redisTemplate.opsForHash().get("codes",tagName).toString();
    }

    //批量存多个信号的快照数据
    public Map<String,Object> saveTagShots(List<TagDetail> tagDetails){
        List<Integer> tagIds = new ArrayList<>();
        List<HDRecord> records = new ArrayList<>();
        HDErrcode errcode = new HDErrcode();
        Map<String,Object> result = new HashMap<>();
        List<Integer> resultCode = new ArrayList<>();
        for(TagDetail tagDetail : tagDetails){
            int tagId = tagDetail.id;
            tagIds.add(tagId);
            HDRecord record = new HDRecord();
            record.setBelongTagID(tagId);
            record.setDataType(tagDetail.tagDataType);
            record.setQuality(tagDetail.quality);
            record.setValueStr(tagDetail.valueStr);
            //记录时间精确到毫秒
            //record.setSecond(TimeConvertUtil.timeToLong(tagDetail.second));
            records.add(record);
        }
        try {
            HDDataWriter writer = applicationContext.getBean(HDDataWriter.class);
            resultCode = writer.saveSnapshots(tagIds, records, errcode);
            for(int i=0;i<resultCode.size();i++){
                result.put(tagIds.get(i).toString(),resultCode.get(i));
            }
        } catch (HDSdkException e) {
            e.printStackTrace();
        }

//        result = resultCode
//                .stream()
//                .collect(Collectors.toMap(TagDetail::getId,Function.identity()));
        return result;
    }

    //查询单个信号快照数据
    public String getTagValueById(int tagId){
        HDDataProvider provider = applicationContext.getBean(HDDataProvider.class);
        HDRecord record = null;
        try {
            record = provider.querySnapshotByTagID(tagId);
        } catch (HDSdkException e) {
            e.printStackTrace();
        }
        return record.getValueStr();
    }
}
